package com.yunhe.tianhe.controller.cars;


import com.yunhe.commons.dto.JSONResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by Administrator on 2017/11/14 0014.
 */
@org.springframework.stereotype.Controller
@RequestMapping("/")
public class StorageController {
    @RequestMapping("upload")
    @ResponseBody
    public JSONResponse upload (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        ArrayList<Object> list = new ArrayList <>();
        req.setCharacterEncoding("utf-8");
        Collection<Part> parts = req.getParts();     //获取提交过来的文本域
        File file = new File("E:\\fs");
        if (!file.exists()){
            file.mkdirs();
        }
        for (Part part:parts){
            String fileName = part.getSubmittedFileName();  //获取上传文件的真实名字
            String suffix = fileName.substring(fileName.lastIndexOf("."));  //获取后缀名
            String a =  System.currentTimeMillis()+ suffix ;  //时间戳组成新的名字
            part.write(file+File.separator+a);    //写入
            list.add(a);
        }

        JSONResponse success = JSONResponse.success("上传成功！", list);
        return success;
    }

    @RequestMapping("download")
    public void download(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        String fileName = (String) req.getParameter("FileName");     //获取需要下载的名字
        File file = new File("E:\\fs\\"+fileName);          //拼接，找到需要下载的对象
//        String encode = URLEncoder.encode(fileName, "utf-8");      //防止乱码
//        resp.setHeader("content-disposition","attachment;filename="+encode);    //让浏览器以附件的形式下载，并指定名字
        if (file.exists()){
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();
            byte [] bytes = new byte[1024*1024];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }
            outputStream.flush();
            outputStream.close();
        }
    }


}
